import Entity.MessageDTO;
import Entity.OpenidDTO;
import com.alibaba.fastjson.JSON;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import Entity.UserDTO;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.persistence.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import java.io.BufferedReader;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import httpclient.QuickStart;

@WebServlet(urlPatterns = {"/login/dgut"})
public class Servlet_Return extends HttpServlet{
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {

        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//向http://cas.gemcho.com/ssoapi/v2/checkToken发送post请求获取用户信息
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        String token=req.getParameter("token");
        String appid="javaee";
        String appsecret = "b3b52e43ccfd";
        String userip = req.getRemoteAddr();     //获取本地ip
        String url = "https://cas.dgut.edu.cn/ssoapi/v2/checkToken";
        List<NameValuePair> s = new ArrayList<>();
        s.add(new BasicNameValuePair("token",token));
        s.add(new BasicNameValuePair("appid",appid));
        s.add(new BasicNameValuePair("appsecret",appsecret));
        s.add(new BasicNameValuePair("userip",userip));
        String json = QuickStart.post(url,s);


        OpenidDTO oid= JSON.parseObject(json,OpenidDTO.class);
        //System.out.println(oid);
        if(oid.getError()!=null){
            String access_token = oid.getAccess_token();
            String openid = oid.getOpenid();
            List<NameValuePair> s1 = new ArrayList<>();
            s1.add(new BasicNameValuePair("access_token",access_token));
            s1.add(new BasicNameValuePair("openid",openid));
            String json1=QuickStart.post("https://cas.dgut.edu.cn/oauth/getUserInfo",s1);
            Jsonb jsonb= JsonbBuilder.create();
            UserDTO user=jsonb.fromJson(json1,UserDTO.class);
            // UserDTO user=JSON.parseObject(json1, UserDTO.class);

            if(user.getError()!=null){
                UserDTO userDTO=new UserDTO("1","","","","","", null);
                Jsonb jsonb1 = JsonbBuilder.create();
                String jsonPerson = jsonb1.toJson(userDTO);
                resp.getWriter().write(jsonPerson);
            }
            else {
                MessageDTO message=(MessageDTO)req.getSession().getAttribute("LocalUser");
                if(message==null) {
                    //关联账号

                    EntityManager em = getEntityManager();
                    EntityTransaction tx = em.getTransaction();
                    String name = user.getusername();
//                  System.out.println("222");
                    boolean flag = false;
                    try {
                        Query query = em.createQuery("select mes from MessageDTO mes where mes.name = :name");
                        query.setParameter("name", name);
                        List list = query.getResultList();
                        //判断莞工账号是否存在数据库中
                        if (list.size() != 0) {
                            for (Object i : list) {
                                message = (MessageDTO) i;
                                if (message.getname().equals(name) || message.getInfo().equals(user)) {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        //若不存在,则利用莞工账号建立新的本地用户
                        if (!flag) {
//                          System.out.println("111");
                            message = new MessageDTO(user.getusername(), null, "123456", null, "img1.jpg", user);
                            try {
//                              System.out.println("111");
                                tx.begin();
                                em.persist(user);
                                em.persist(message);
                                tx.commit();
                            } catch (Exception e) {
                                tx.rollback();
                                e.printStackTrace();
                            } finally {
                                em.close();
                            }
                        }
                        req.getSession().setAttribute("LocalUser", message);
                        resp.sendRedirect("http://localhost:8080/userinfo.jsp");
                    } catch (Exception e) {
                        resp.sendRedirect("http://localhost:8080/error.jsp");
                    }
                }
                else {
                    String name = message.getname();
                    String username = user.getusername();
                    EntityManager em = getEntityManager();
                    EntityTransaction tx = em.getTransaction();
                    message=em.find(MessageDTO.class,name);
                    UserDTO u=em.find(UserDTO.class,username);
                    if(message!=null)
                    {
                        tx.begin();
                        if (u==null) {
                            em.persist(user);
                        }
                        message.setInfo(user);
                        em.persist(message);
                        tx.commit();
                        em.close();
                    }
                    else {
                        resp.sendRedirect("http://localhost:8080/error.jsp");
                    }
                    req.getSession().setAttribute("LocalUser", message);
                    resp.sendRedirect("http://localhost:8080/userinfo.jsp");
                }

            }

        }
        else{
            OpenidDTO myDTO=new OpenidDTO("1","token不存在或已过期","","");
            Jsonb jsonb = JsonbBuilder.create();
            String jsonPerson = jsonb.toJson(myDTO);
            resp.getWriter().write(jsonPerson);

        }

    }

}
